﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ChinessChess
{
   public class CNetWorks
    {
        private Socket client;
        private byte[] data = new byte[512];
        private Thread receiver;
        private Form1 form;
        private StateConnection state = StateConnection.Breaken;
        private string ip = "";
        public StateConnection Connection
        {
            get { return state; }
            set { state = value; }

        }

       public CNetWorks() { 

       }
       public CNetWorks(Form1 f)
       {
           this.form = f;
       }

       #region Server
       public void Listen()
       {
           try
           {
               form.SetStatusMessage("Dang cho ket noi...");
               Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

               IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
               newsock.Bind(iep);
               newsock.Listen(2);
               state = StateConnection.Connecting;
               newsock.BeginAccept(new AsyncCallback(AcceptConn), newsock);
           }
           catch (Exception e)
           {
               MessageBox.Show(e.Message.ToString());
           }
       }

       void AcceptConn(IAsyncResult iar)
       {
           Socket oldserver = (Socket)iar.AsyncState;
           client = oldserver.EndAccept(iar);
           form.SetStatusMessage("Da duoc ket noi.");
           state = StateConnection.Connected;
           receiver = new Thread(new ThreadStart(ReceiveData));
           receiver.Start();
       }
       #endregion server

       public void CloseConnect()
       {
           client.Disconnect(false);
           state = StateConnection.Breaken;
           return;
       }

       #region Client
       public void ConnectTo(string ipServer)
       {
           ip = ipServer;
           form.SetStatusMessage("Dang ket noi...");
           client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           try
           {
               IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ipServer), 9050);
               client.BeginConnect(iep, new AsyncCallback(Connected), client);
           }
           catch
           {
              form.SetStatusMessage("Khong the ket noi!");
           }
       }
       //
       private void Connected(IAsyncResult iar)
       {
           try
           {
               client.EndConnect(iar);
               Thread receiver = new Thread(new ThreadStart(ReceiveData));
               receiver.Start();
           }
           catch (SocketException)
           {
             
           }
       }
       #endregion client
       #region sent & received packet data
       private void SendData(IAsyncResult iar)
       {
           Socket remote = (Socket)iar.AsyncState;
           int sent = remote.EndSend(iar);
       }
       public void sendPacket(string packet)
       {
           try
           {
               byte[] Sent = Encoding.ASCII.GetBytes(packet);
               client.BeginSend(Sent, 0, Sent.Length, 0, new AsyncCallback(SendData), client);
           }
           catch (SocketException e)
           {
               state = StateConnection.Breaken;
               MessageBox.Show(e.Message.ToString());
           }
       }
       private void ReceiveData()
       {
           int recv;
           string packData = "";

           try
           {
               while (true)
               {
                   recv = client.Receive(data);
                   packData = Encoding.ASCII.GetString(data, 0, recv);


                   if (packData.ToString().Equals(""))
                       return;

                   if (packData.StartsWith("@"))
                   {
                      
                       return;
                   }
                   else
                   {
                       switch (packData.ToString())
                       {
                           case "N"://new game
                               {
                                   form.NewGame();
                                   form.Refresh();
                               } break;
                           case "X":
                               {
                                   
                                   MessageBox.Show(CMessage.strCloseGame);
                                   form.Pause = true;
                                   CloseConnect();
                                   form.Close();
                               }; break;
                           case "W_WIN":
                               {
                                   MessageBox.Show(CMessage.strNewGame);
                                 
                               } break;
                           case "B_WIN":
                               {
                                   MessageBox.Show(CMessage.strNewGame);
                                  // form.Pause = true;
                               } break;
                           default:
                               {
                                  // net.sendPacket(indexNew + "," + indexOld + ",1," + newpoint.X + "," + newpoint.Y + "," + _OriginPoint.X + "," + _OriginPoint.Y + "," + cControl.Index + "," + color);
                                   string[] point = packData.Split(',');
                                   int indexNew =int.Parse(point[0]);
                                   int indexOld = int.Parse(point[1]);
                                   int User = int.Parse(point[2]);
                                   int newPointX = int.Parse(point[3]);
                                   int newPointY = int.Parse(point[4]);
                                   int oldPointX = int.Parse(point[5]);
                                   int oldPointY = int.Parse(point[6]);
                                   int index = int.Parse(point[7]);
                                   int color = int.Parse(point[8]);
                                   Point newPoint = new Point(newPointX, newPointY);
                                   Point oriPoint = new Point(oldPointX, oldPointY);
                                   if (User == 1)
                                   {
                                       form.Process(index, indexNew, indexOld, newPoint, oriPoint, color);
                                       form.Player = ChessColor.black;
                                   }
                                   else
                                   {
                                       form.Process(index, indexNew, indexOld, newPoint, oriPoint, color);
                                       form.Player = ChessColor.white;
                                   }

                               } break;
                       }//end switch
                   }
               }//end while
           }//end try
           catch (Exception e)
           {
               MessageBox.Show(e.Message.ToString());
           }
           client.Close();
           return;
       }
       #endregion sent & received packet data
    }
}
